package com.demo.tx.local.service;

import com.demo.tx.local.entity.User;
import com.demo.tx.local.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 声明式事务测试
 */
@Slf4j
@Service
public class DeclarativeTransactionService {

    @Resource
    private DeclarativeTransactionService declarativeTransactionService;
    @Resource
    private UserMapper userMapper;

    /**
     * 测试循环依赖本身，通过调用依赖注入的本身方法，会抛出异常，验证事务是否回滚
     *
     * @param userId 用户ID
     */
    public void methdoA(Long userId) {
        declarativeTransactionService.methodB(userId);
    }

    @Transactional
    public void methodB(Long userId) {
        User user = new User();
        user.setUserName("aaa");
        user.setUserId(userId);

        userMapper.insert(user);
        log.info("数据保存完毕");

        throw new RuntimeException("异常");
    }
}
